import React, { useEffect } from 'react';

class ScrollView extends React.Component {
  node = null;
  constructor(props) {
    super(props);
    this.state = {
      list: [],
    };
  }

  static getDerivedStateFromProps(nextProps) {
    return {
      list: nextProps.list || [],
    };
  }

  componentDidMount() {
    this.node.addEventListener('scroll', this.handleScroll);
  }

  componentWillUnmount() {
    this.node.removeEventListener('scroll', this.handleScroll);
  }

  handleScroll = (e) => {
    // 判断是否到底
    const { scroll } = this.props;
    scroll && scroll(e);
    this.handleScrollTBottom(e);
  };

  handleScrollTBottom(e) {
    const { scrollHeight, scrollTop, offsetHeight } = this.node;
    if (scrollHeight <= scrollTop + offsetHeight) {
      this.props.scrollToBottom && this.props.scrollToBottom();
    }
  }

  getSnapshotBeforeUpdate() {
    return this.node.scrollHeight;
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    console.log(this.node.scrollHeight, snapshot);
  }

  render() {
    const { list } = this.state;
    const style = {
      height: 100,
      border: '1px solid red',
    };
    const divStyle = {
      overflow: 'auto',
      height: 150,
    };
    return (
      <div style={divStyle} ref={(node) => (this.node = node)}>
        {list.map((item) => (
          <div style={style}>
            <p>{item.name}</p>
            <p>{item.age}</p>
          </div>
        ))}
      </div>
    );
  }
}

export default ScrollView;
